// 公用的http请求方法
import axios from 'axios'
import config from 'service/config'
import util from 'service/util/index.js'

// 请求基本设置
var baseConf = {
    baseURL: config.baseURL,
    withCredentials: true
}

// get请求默认参数
var defaultParams = {
    apiVersion: config.apiVersion,
    devName: config.devName
}
// post请求默认参数
var defaultData = {
    apiVersion: config.apiVersion,
    devName: config.devName
}
// post请求默认配置
var defaultPostConfig = {
    headers: {
        'Content-Type': 'multipart/form-data; charset=UTF-8'
    },
    responseType: 'json',
    transformRequest: [function (data) {
        var formData = new window.FormData()
        for (var k in data) {
            formData.append(k, data[k])
        }
        return formData
    }]
}

/* 在创建实例时设置配置默认值 */
var instance = axios.create(baseConf)

export default {
    get(url, params, ajaxConfig) {
        ajaxConfig = ajaxConfig || {}
        params = params || {}
        Object.assign(params, defaultParams)
        params.noCache = new Date().getTime()
        ajaxConfig.params = params
        return instance.get(url, ajaxConfig).then(rep => {
            if (rep.data.code == 'F') {
                $toast.show(rep.data.msg)
            }
            return rep
        }).catch(err => {
            $toast.show('网络异常')
            return err
        })
    },
    /**
     * post请求
     * @param {*String} url 路径
     * @param {*Object} data 数据
     * @param {*Array} orders 排序
     * @param {*Object} ajaxConfig ajax设置
     */
    
    post(url, data, orders, ajaxConfig) {
        var postData = {}
        var finalConfig = {}
        ajaxConfig = ajaxConfig || {}
        data = data || {}
        orders = orders || []
        Object.assign(postData, defaultData, data)
        Object.assign(finalConfig, defaultPostConfig, ajaxConfig)
        postData.md5Sign = util.getMd5Sign(postData, orders, config.md5ConfigStr)
        return instance.post(url, postData, finalConfig).then(res => {
            // 开发-查看返回结果
            var { code } = res.data
            // 用户未登录或登录过期
            if (code == 'N') {
                $router.replace({
                    name: 'user_login',
                    params: {
                        redirect: true
                    }
                })
                $store.dispatch('userClear')
                $store.dispatch('borrowClear')
                $store.dispatch('orderClear')
            }
            return res
        })
    }
}